#include <myheader_c_plus.h>
using std::cout;
using std::endl;
union MyString{
    char * _pchar;
    char mychar[16];
};
//当长度小于15时存储在对象内部，字符串大小大于15时存储在堆空间
class SSO{
public:

    //无参构造函数
    SSO()
    :_size(0)
    {
        memset(mystring.mychar,0,sizeof(mystring.mychar));
    }


    //构造函数
    SSO(const char * pchar)
    :_size(strlen(pchar))
    {
        if(strlen(pchar) > 15){
            mystring._pchar = new char [strlen(pchar) + 1]();
            strcpy(mystring._pchar, pchar);
        }else{
            strcpy(mystring.mychar, pchar);
        }
    }


    //拷贝构造函数
    SSO(const SSO & rhs){
        _size = rhs._size;
        if(rhs._size > 15){
            mystring._pchar = new char[rhs._size + 1]();
            strcpy(mystring._pchar, rhs.mystring._pchar);   
        }else{
            memset(mystring.mychar, 0, sizeof(mystring.mychar));
            strcpy(mystring.mychar, rhs.mystring.mychar);
        }
    }



    //赋值运算符函数
    SSO & operator=(const SSO & rhs){
        if(this != &rhs){
            if(_size > 15){
                delete [] mystring._pchar;
            }else{
                memset(mystring.mychar, 0, sizeof(mystring.mychar));
            }

            if(rhs._size > 15){
                mystring._pchar = new char [strlen(rhs.mystring._pchar) + 1]();
                strcpy(mystring._pchar, rhs.mystring._pchar);
            }else{
                strcpy(mystring.mychar, rhs.mystring.mychar);
            }
            _size = rhs._size;
        }
        return *this;
    }


    //析构函数
    ~SSO(){
        if(_size > 15){
            delete [] mystring._pchar;
            mystring._pchar = nullptr;
        }
    }

    void getChar_size(){
        if(_size > 15){
            cout << "size = " <<_size << " "<< "str = " << mystring._pchar << endl;
        }else{
            cout << "size = " <<_size << " " <<"str = " << mystring.mychar << endl;
        }
    }

private:
    int _size; 
    MyString mystring;    
};
int main(int argc, char *argv[])
{
    SSO sso("hello");
    sso.getChar_size();
    SSO sso2("helloworldhellojavahellojavascript");
    sso2.getChar_size();
    SSO sso3 = sso;
    sso3.getChar_size();
    SSO sso4 = sso2;
    sso4.getChar_size();
    cout << "============" << endl;
    sso = sso2;
    sso.getChar_size();
    sso2 = sso3;
    sso2.getChar_size();
    sso2 = sso4;
    cout << "sso2 "; sso2.getChar_size();
    SSO sso5("hellojava");
    SSO sso6("hellogrok");
    sso5 = sso6;
    cout << "sso5: ";   sso5.getChar_size();

    return 0;
}

